import axios from 'axios'
import {Message} from 'element3'
import store from '@/store'
import {getToken} from '@/utils/auth'

const service = axios.create({
  baseURL: import.meta.env.VITE_APP_BASE_API,
  timeout: 5000
})

service.interceptors.request.use(
  config => {
    if (store.getters.token) {
      config.headers['X-Token'] = getToken()
    }
    return config
  },
  error => {
    console.log(error)
    return Promise.reject(error)
  }
)

service.interceptors.response.use(
  response => {
    const res = response.data
    if (res.code !== 2000) {
      console.log('接口错误：', res.message)
      Message.error(res.message)
      return Promise.reject(new Error(res.message || 'Error'))
    } else {
      return res.data
    }
  },
  error => {
    console.log('接口错误：', error)
    Message(error.message || '服务器错误！')
    return Promise.reject(error)
  }
)

export default service

